from playwright.sync_api import sync_playwright
#from playwright.sync_api import Playwright, sync_playwright, expect
import requests
import os
import parsel
import re
import time
#创建文件夹


save_dir = '日月同错'
if save_dir not in os.listdir('./'):
    os.mkdir(save_dir)
#https://godamh.com/manga/riyuetongcuo-dinianmiao
url = 'https://baozimh.org/manga/riyuetongcuo-dinianmiao'
headers = {
    'User-Agent' : 'Mozilla/5.e (Windons NI 18.8; Winb4;x54)AppleWebkit/537.36(KHIML,like Gecko) Chrome/113.0.0.8 Safari/537.36', 'x-requested-with': 'XMLiIttpHequest',
}
        
response = requests.get(url=url,headers=headers)
response.encoding = "utf-8"
selector = parsel.Selector(response.text)
href_list = selector.xpath('//div[@class="chapteritem w-full "]/a/@href').getall()
href_name = selector.xpath('//div[@class="chapteritem w-full "]/a/div[1]/span[1]/text()').getall()
href_list_0 = href_list[:1]
href_name_0 = href_name[:1]
print(href_list_0,href_name_0)
#href_list_0 = href_list[3]
#href_name_0 = href_name[3]
for href,name in zip(href_list_0,href_name_0):
    #print(href,name)
    #new_title = re.sub(r'[\/:*?"<>|]','',name)
    name = name.strip()
    new_title = re.sub(r'[\/:*?"<>|]','',name)
    chapter_save_dir = os.path.join(save_dir, new_title)
    if new_title not in os.listdir(save_dir):
        os.mkdir(chapter_save_dir)  
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        page = browser.new_page()
        page.goto(href)
        '''
        #page.frame_locator("iframe >> nth=2").get_by_text("Close").click()
        frame = page.frame_locator("iframe >> nth=1")
    # 使用 wait_for 方法，等待 span 元素出现，超时时间为 5 秒
        span_element = frame.locator("span").first.wait_for(timeout=5000)
        page.frame_locator("iframe >> nth=2").locator("span").nth(2).click()
        iframe = page.frame_locator("iframe >> nth=1").locator("div")
        with iframe:
            # 使用evaluate执行JavaScript代码，阻止所有的点击事件
            iframe.evaluate("""
            () => {
                const iframeDocument = document;
                iframeDocument.addEventListener('click', (event) => {
                    event.preventDefault(); // 阻止默认行为
                    event.stopPropagation(); // 阻止事件冒泡
                }, true); // 使用true作为第三个参数表示在捕获阶段处理事件
            }
            """)
            '''
        frame = page.frame_locator("iframe >> nth=1")
        span_element = frame.locator("span").first.wait_for(timeout=5000)
        page.frame_locator("iframe >> nth=1").locator("span").nth(2).click()
        #iframe = page.frame_locator("iframe >> nth=1")
        #div_element = iframe.locator("div").filter(has_text="快橙 的匿名VPN服务保护您的网络身份AdContinueClose").nth(1)
        element = page.query_selector_all('//div[@class="w-full h-full"]/img')
        count = 0
        for elements in element:
         try:
             span_element = frame.locator("span").first.wait_for(timeout=100)
             page.frame_locator("iframe >> nth=1").locator("span").nth(2).click()
         except:
              img_page = elements.get_attribute('alt')
              #print(img_page)
              page.get_by_role("img",name=img_page,exact=True).hover()
              #page.get_by_role("img",name=img_page,exact=True).scroll_into_view_if_needed()
          #page.locator(img_page).scroll_into_view_if_needed()
              time.sleep(1)
              img_url = elements.get_attribute('src')
              img = requests.get(url=img_url,headers=headers).content
              title = '%03d.jpg' % (count + 1)
              pic_save_path = os.path.join(chapter_save_dir, title)
              with open(pic_save_path,mode='wb') as f:
                f.write(img)
                count+=1
                print('保存完成：', title)
             
       
        
        browser.close()
        print('保存-----完成：',name)

